package cn.me.alphamq.broker.core.commitlog;

import cn.me.alphamq.broker.cache.Container;
import cn.me.alphamq.broker.store.VersionHolder;
import cn.me.alphamq.common.entity.Message;
import cn.me.alphamq.common.util.AssertUtil;

import java.io.IOException;

/**
 * 追加 CommitLog 的处理器
 *
 * @author f
 */
public class CommitLogAppendHandler {

    private CommitLogMMapFileModelManager commitLogMMapFileModelManager;

    /**
     * 预映射指定 topic 的 CommitLog 文件，提升 MQ 的性能
     *
     * @param topicName
     * @throws IOException
     */
    public void prepareMMapLoading(String topicName) throws IOException {
        commitLogMMapFileModelManager = Container.getCommitLogMMapFileModelManager();
        CommitLogMMapFileModel commitLogMMapFileModel = new CommitLogMMapFileModel();
        AssertUtil.isNotNull(commitLogMMapFileModel, "invalid topic [" + topicName + "]");
        commitLogMMapFileModel.loadFileInMMap(topicName);
        commitLogMMapFileModelManager.put(topicName, commitLogMMapFileModel);
    }

    /**
     * 将消息追加到指定 topic 的 CommitLog 文件中
     *
     * @param message 指定的消息
     */
    public void appendMsg(Message message) throws Exception {
        CommitLogMMapFileModel commitLogMMapFileModel = commitLogMMapFileModelManager.get(message.getTopic());
        AssertUtil.isNotNull(commitLogMMapFileModel, "topic is invalid!");
        // 持久化消息
        commitLogMMapFileModel.writeContent(message);
        // 自增版本号
        VersionHolder.inc();
    }

}
